package org.lzfto.flink.demo.controller;

import org.lzfto.flink.demo.business.orders.Order;
import org.lzfto.flink.demo.business.orders.OrderService;
import org.lzfto.flink.demo.common.data.PageData;
import org.lzfto.flink.demo.common.result.PubResult;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Lazy
@RestController
@RequestMapping("/orders")
public class OrderController {
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping("/query")
    public PageData<Order> selectByPage(int pageNo, int pageSize, @RequestBody Order param) {
        return orderService.findAll(param,pageNo,pageSize);
    }

    @GetMapping("/queryById")
    public Order findById(@RequestParam int id) {
        return orderService.findById(id);
    }
    
    @GetMapping("/countTargetOrder")
    public PubResult<Integer> countTargetOrder() {
        return orderService.countTargetOrder();
    }

    /**
     * 释放MQTT锁.主要用于释放/start-send-to-mqtt中的锁
     * </br>需要谨慎使用
     * @return 总是返回flag=1的result。但是是否成功应该看data(Boolean)
     */
    @GetMapping("/release-mqttlock")
    public PubResult<Boolean> releaseMqttLock() {
        return orderService.releaseMqttLock();
    }

    @SuppressWarnings("rawtypes")
	@PostMapping("/save")
    public PubResult save(@RequestBody Order order) {
        orderService.save(order);
        return PubResult.ok("保存成功");
    }

    @SuppressWarnings("rawtypes")
	@PostMapping("/delete")
    public PubResult deleteById(@RequestParam int id) {
        orderService.deleteById(id);
        return PubResult.ok("删除成功");
    }

    /**
     * 从数据库读取数据并发送给mqtt服务器以及websocket客户但
     * @param pageQty     获取数据分页数量
     * @param pageSize    获取数据分页大小
     * @param sendSocket  是否发送到websocket客户端
     * @param testNo      测试编码 {@linkplain}
     * @param interval    发送间隔<=0，表示不发送
     * @return
     */
    @PostMapping("/start-send-to-mqtt")
    public PubResult<String> startSendToMqtt(
    		@RequestBody  Order order,
    		@RequestParam int pageQty,
    		@RequestParam int pageSize,
    		@RequestParam int sendSocket,
    		@RequestParam int testNo,
    		@RequestParam(required=false) Integer interval
    		) {
        return orderService.sendDataToMqtt(order==null?new Order():order,pageQty,pageSize,sendSocket,interval,testNo);
    }
}
